﻿using System.Collections.Generic;
using System.Linq;
using PaceR.Core.EntityStorage;
using PaceR.Examples.MVC.Models;
using PaceR.Web.EntityStorage;

namespace PaceR.Examples.MVC.Library
{
    public static class UserProfileAgent
    {
        private static EntityStore _store = new SessionStorage();

        public static void Save(UserProfile profile)
        {
            var users = GetAllUsers();
            var user = users.FirstOrDefault(u => u.Username == profile.Username);
            if (user != null)
            {
                users.Remove(user);
            }
            users.Add(profile);
        }

        public static UserProfile GetUser(string username)
        {
            return GetAllUsers().FirstOrDefault(u => u.Username == username);
        }

        public static IList<UserProfile> GetAllUsers()
        {
            if (_store.GetEntity<IList<UserProfile>>() == null)
                _store.SaveEntity<IList<UserProfile>>(new List<UserProfile>());
            return _store.GetEntity<IList<UserProfile>>();
        }

        public static void DeleteUser(string id)
        {
            var users = GetAllUsers();
            var user = users.FirstOrDefault(u => u.Username == id);
            if (user != null)
                users.Remove(user);
        }
    }
}